package com.develop.data.loan.jpa.attribute.converter;

import com.develop.data.loan.option.LoanTimelineType;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Converter
public class LoanTimelineTypeAttributeConverter implements AttributeConverter<LoanTimelineType, String> {
    private final Map<String, LoanTimelineType> code2constant = new HashMap<>();

    public LoanTimelineTypeAttributeConverter() {
        Arrays.stream(LoanTimelineType.class.getEnumConstants()).forEach(
            enumConstant -> {
                try {
                    Method methodGetCode = LoanTimelineType.class.getDeclaredMethod("getCode");
                    this.code2constant.put(methodGetCode.invoke(enumConstant).toString(), enumConstant);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        );
    }
    

    @Override
    public String convertToDatabaseColumn(LoanTimelineType constant) {
        return constant == null ? null: constant.getCode();
    }

    @Override
    public LoanTimelineType convertToEntityAttribute(String code) {
        return Optional.ofNullable(code)
                .map(code2constant::get)
                .orElse(null);
    }
}

